﻿using Abide.Classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Abide
{
    public partial class UpdateDialog : Form
    {
        public bool DownloadCompleted
        {
            get;
            protected set;
        }
        public string UpdaterFile
        {
            get { return updaterFile; }
        }

        private AssemblyName updateName;
        private string updaterUrl;
        private DateTime updateDate;
        private WebClient downloader;
        private string updaterFile;

        private UpdateDialog()
        {
            InitializeComponent();

            //Check
            if (!Security.IsAdmin())
                Security.ElevateButton(beginButton);
        }
        public UpdateDialog(AssemblyName updateName, string updaterUrl, DateTime updateDate, string updaterFile) :
            this()
        {
            //Setup
            this.updateName = updateName;
            this.updaterUrl = updaterUrl;
            this.updateDate = updateDate;
            this.updaterFile = updaterFile;
            DownloadCompleted = false;
            beginButton.Enabled = true;
        }
        
        private void beginButton_Click(object sender, EventArgs e)
        {
            //Show and Disable
            beginButton.Enabled = false;
            progressBar.Visible = true;
            progressBar.MarqueeAnimationSpeed = 10;

            //Check...
            if (!Security.IsAdmin())
            {
                //Setup
                progressBar.Style = ProgressBarStyle.Marquee;
                progressLabel.Text = "Downloading. Please Wait...";
                Process downloadProcess = null;

                //Start Process
                ThreadPool.QueueUserWorkItem(state =>
                {
                    if (Security.RestartElevated(out downloadProcess, "-sud"))
                        while (!downloadProcess.HasExited)
                            Thread.Sleep(1);
                    Invoke(new MethodInvoker(delegate
                    {
                        DownloadCompleted = File.Exists(updaterFile);
                        Close();
                    }));
                });
            }
            else
            {
                //Prepare
                downloader = new WebClient();
                downloader.DownloadProgressChanged += downloader_DownloadProgressChanged;
                downloader.DownloadFileCompleted += downloader_DownloadFileCompleted;

                //Download
                downloader.DownloadFileAsync(new Uri(updaterUrl), updaterFile);
            }
        }
        private void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //Set
            progressBar.Value = e.ProgressPercentage;
            progressLabel.Text = string.Format("{0}/{1}", e.BytesReceived, e.TotalBytesToReceive);
        }
        private void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //Set
            progressLabel.Text = "Done";

            //Success
            DownloadCompleted = (e.Cancelled == false && e.Error == null);
            Close();
        }
    }
}